/******************** (C) COPYRIGHT 2011 STMicroelectronics ********************
* File Name          : usb_endp.c
* Author             : MCD Application Team
* Version            : V3.3.0
* Date               : 21-March-2011
* Description        : Endpoint routines
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/

/* Includes ------------------------------------------------------------------*/
#ifdef STM32L1XX_MD
#include "stm32l1xx.h"
#else
#include "stm32f10x.h"
#endif /* STM32L1XX_MD */

#include "platform_config.h"
#include "usb_lib.h"
#include "usb_istr.h"
#include "usb_endp.h"
#include "stm32_sdio_sd.h"
#include <stdio.h>
#include <stdint.h>
#include <string.h>

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint8_t Receive_Buffer[64];
uint8_t Transmite_Buffer[64];

extern __IO uint8_t PrevXferComplete;
extern volatile uint8_t TransmiteTimeout;

#define FLASH_START_BANK1	0x08010000
#define FLASH_START_BANK2	0x08090000

#define START_ADDRESS 253551616
#define QUANTITY_OF_63 7280
#define FLASH_SIZE	(QUANTITY_OF_63*63)

uint8_t buffer[512*2] __attribute__ ((aligned (8)));
uint32_t address = START_ADDRESS;
uint8_t count_small = 0;
uint16_t volatile count_nibble = 0;

/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
uint16_t _datta = 0;
uint16_t new_data;
volatile HID_STATE HIDState = HID_TEMPHUM;


void mat_auto()
{
SD_Error SD_Return = SD_OK;
	if( HIDState == HID_SENDDATA )
	{
		if( count_small == 0 ) // Читаем первые 512 байт
		{
//			memcpy( buffer, emul + address, 512 ); // Скопируем 512 байт в

			SD_Return = SD_ReadBlock( buffer, address, 512 );
			SD_Return = SD_WaitReadOperation();
			while( SD_GetStatus() != SD_TRANSFER_OK );
			address += 512;
		}

		Transmite_Buffer[0] = 5;
		memcpy( Transmite_Buffer+1, buffer + count_small*63, 63 );
		count_small++;

		if( count_small == 8 )
			count_small = 0;

		USB_SIL_Write( EP1_IN, (uint8_t *)Transmite_Buffer, 64 );
		SetEPTxValid( ENDP1 );
		PrevXferComplete = 0;

		if( (address > START_ADDRESS + QUANTITY_OF_63*64 - 1) && (count_small == 0) )
		{
			address = START_ADDRESS;
			HIDState = HID_TEMPHUM;
			LED_GREEN_OFF();
			TIM_Cmd( TIM6, DISABLE );
		}
	}
}

/*******************************************************************************
* Function Name  : EP1_OUT_Callback.
* Description    : EP1 OUT Callback Routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
NVIC_InitTypeDef NVIC_InitStructure;

void EP1_OUT_Callback(void)
{
	/* Read received data (2 bytes) */
	USB_SIL_Read(EP1_OUT, Receive_Buffer);
	SetEPRxStatus(ENDP1, EP_RX_VALID);


SD_Error SD_Return = SD_OK;
	if( HIDState == HID_RECEIVEDATA )
	{
		count_nibble++;
		memcpy( buffer + count_small*63, Receive_Buffer+1, 63 );
		count_small++;


		new_data = Receive_Buffer[1] << 8;
		new_data |= Receive_Buffer[2];

		if( _datta != new_data )
		{
			LED_RED_ON();
		}
		_datta++;

		if( count_small == 8 ) // Заполнен весь буффер 512 байт.
		{
			count_small = 0;

			SD_Return = SD_WriteBlock( buffer, address, 512 );
			SD_Return = SD_WaitWriteOperation();
			while(SD_GetStatus() != SD_TRANSFER_OK);

			address += 512;
			if( address > START_ADDRESS + QUANTITY_OF_63*64 - 1 )
			{
				_datta = 0;
				address = START_ADDRESS;
				HIDState = HID_TEMPHUM;
				LED_GREEN_OFF();
			}
		}
	}


	switch( Receive_Buffer[0] )
	{
		case 1:
			if( Receive_Buffer[1] == 0 )
				LED_GREEN_OFF();
			else
				LED_GREEN_ON();
			break;

		case 2:
			if( Receive_Buffer[1] == 0 )
				LED_RED_OFF();
			else
				LED_RED_ON();
			break;
		default:
			break;
	}

	if( Receive_Buffer[0] == 4 )
	{
		// Пришли данные от компы.
		if( (Receive_Buffer[1] == 1) && (HIDState == HID_TEMPHUM) )
		{
//			Начать чтение памяти и сливание ее в компу.
			HIDState = HID_SENDDATA;
			LED_GREEN_ON();

			RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM6, ENABLE );
			DBGMCU_Config( DBGMCU_TIM6_STOP, ENABLE );

			TIM_PrescalerConfig( TIM6, 3599, TIM_PSCReloadMode_Update ); //10 kHz
			TIM_SetAutoreload( TIM6, 149 ); // 15 ms
			TIM_ITConfig( TIM6, TIM_IT_Update, ENABLE );

			NVIC_InitStructure.NVIC_IRQChannel = TIM6_IRQn;
			NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
			NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
			NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
			NVIC_Init( &NVIC_InitStructure );

			TransmiteTimeout = TRUE;
		}

		if( (Receive_Buffer[1] == 0xAA) && (HIDState == HID_TEMPHUM) )
		{
//			Начать запись из эндпоинта во FLASH
			HIDState = HID_RECEIVEDATA;
			LED_GREEN_ON();
		}
	}
}

/*******************************************************************************
* Function Name  : EP1_IN_Callback.
* Description    : EP1 IN Callback Routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void EP1_IN_Callback(void)
{
	PrevXferComplete = 1; // Передача на комп завершена
}
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/

